package day11.handler.simpleChannelHandler.request;

import day11.handler.simpleChannelHandler.response.GroupMessageResponseHandler;
import day11.packet.request.GroupMessageRequestPacket;
import day11.packet.response.GroupMessageResponsePacket;
import day11.util.session.GroupSession;
import day11.util.session.SessionUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

/**
 * @author chenshijie
 * @date 2024/1/3 10:39
 */

public class GroupMessageRequestHandler extends SimpleChannelInboundHandler<GroupMessageRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupMessageRequestPacket groupMessageRequestPacket) throws Exception {

        GroupMessageResponsePacket groupMessageResponsePacket = new GroupMessageResponsePacket();
        int groupId = groupMessageRequestPacket.getGroupId();
        if (SessionUtil.hasGroup(groupId)) {
            groupMessageResponsePacket.setSuccess();
            GroupSession groupSession = SessionUtil.getGroupSession(groupId);
            ChannelGroup channelGroup = groupSession.getChannelGroup();
            groupMessageResponsePacket.setGroupId(groupId);
            groupMessageResponsePacket.setFromUser(groupMessageRequestPacket.getFromUser());
            groupMessageResponsePacket.setMessage(groupMessageRequestPacket.getGroupMessage());
            channelGroup.writeAndFlush(groupMessageResponsePacket);
        } else {
            groupMessageResponsePacket.setFail();
            groupMessageResponsePacket.setMessage("找不到该群");
            System.out.println("没有该群【"+ groupId +"】");
            ctx.channel().writeAndFlush(groupMessageResponsePacket);
        }
    }
}
